package com.springboot.springbootredis.valid;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * @Author: TongRui乀
 * @Date: 2019/1/15 11:10
 * @description：
 */
public class DateTimeValidator implements ConstraintValidator<DateTimeFormat, String> {

    private DateTimeFormat dateTimeFormat;

    @Override
    public void initialize(DateTimeFormat constraintAnnotation) {
        this.dateTimeFormat = constraintAnnotation;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {

        // 如果 value 为空则不进行格式验证，为空验证可以使用 @NotBlank @NotNull @NotEmpty 等注解来进行控制，职责分离
        if (value == null) {
            return true;
        }
        String format = dateTimeFormat.format();
        if (value.length() != format.length()) {
            return false;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        try {
            simpleDateFormat.parse(value);
        } catch (ParseException e) {
            return false;
        }
        return true;

    }
}
